<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item>
          <Search :allOpts="formInline.allOpts" v-model="formInline.cOpts" @blur="search"></Search>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="handleAdd">创建</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" :disabled="butStatus.update" @click="handleUpdate">修改</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" :disabled="butStatus.rm" @click="handleDelete">删除</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <template>
      <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55">全选</el-table-column>
        <el-table-column label="源ID" prop="user_datasource_id"></el-table-column>
        <el-table-column label="名称" prop="datasource_name"></el-table-column>
        <el-table-column label="数据库类型" prop="dbtype">
          <template scope="scope">
            <span>{{scope.row.dbtype | databaseType}}</span>
          </template>
        </el-table-column>
        <el-table-column label="ip地址" prop="ip"></el-table-column>
        <el-table-column label="端口" prop="port"></el-table-column>
        <el-table-column label="数据库名" prop="dbname"></el-table-column>
        <el-table-column label="用户名" prop="db_user_name"></el-table-column>
        <!--<el-table-column label="密码" prop="dbpwd" ></el-table-column>-->
        <el-table-column label="操作" width="125">
          <template scope="scope">
            <el-button @click="toTest(scope)" type="primary" size="small">测试连接</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!--分页-->
    <el-col :span="24" class="toolbar" style="padding-bottom:10px;">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.start_index"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pagination.page_count"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.count"
        style="float:right"></el-pagination>
    </el-col>

    <!--修改界面-->
    <el-dialog :title="formTitle" v-model="dialogFormVisible" size="tiny" @close="resetForm">
      <el-form :model="form" :rules="rules" ref="form">
        <!--<el-form-item label="源ID" prop="user_datasource_id" :label-width="formLabelWidth">
          <el-input v-model="form.id" auto-complete="off"></el-input>
        </el-form-item>-->
        <el-form-item label="名称" prop="datasource_name" :label-width="formLabelWidth">
          <el-input v-model="form.datasource_name"
                    @blur="validateDatasourceNameHttp"></el-input>
          <div>
            <span :class="form.isSuccess=='1'?'zhHelpTips':'zhHelpTipsErr'">{{form.zhHelpTips}}</span>
          </div>
        </el-form-item>
        <!--<el-form-item label="版本" prop="version" :label-width="formLabelWidth">
          <el-select v-model="form.version" placeholder="请选择">
            <el-option v-for="item in versionOptions" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item label="数据库类型" prop="dbtype" :label-width="formLabelWidth">
          <el-select v-model="form.dbtype" placeholder="请选择" style="width: 100%">
            <el-option label="mysql" value="1"></el-option>
            <el-option label="oracle" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="IP地址" prop="ip" :label-width="formLabelWidth">
          <el-input v-model="form.ip"></el-input>
        </el-form-item>
        <el-form-item label="端口" prop="port" :label-width="formLabelWidth">
          <el-input v-model="form.port"></el-input>
        </el-form-item>
        <el-form-item label="数据库名" prop="dbname" :label-width="formLabelWidth">
          <el-input v-model="form.dbname"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="db_user_name" :label-width="formLabelWidth">
          <el-input v-model="form.db_user_name"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="dbpwd" :label-width="formLabelWidth">
          <el-input v-model="form.dbpwd" type="password"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm">取 消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">{{btnEditText}}</el-button>
      </div>
    </el-dialog>

    <!--测试连接-->
    <el-dialog :title="formTitle01" v-model="testContentVisible">
      <el-progress :text-inside="true" :stroke-width="18" :percentage="percentage" status="success"></el-progress>
    </el-dialog>
  </section>
</template>

<script>
  import util from '../../common/util'
  import C from '../../common/cfg'
  import dao from '../../common/dao'
  import NProgress from 'nprogress'
  import Search from '../../components/Search.vue'
  export default {
    components: {Search},
    data() {
      return {
        versionOptions: [{
          label: 'spark 1.6.2',
          value: '1'
        }, {
          label: 'spark 1.6.3',
          value: '2'
        }],
        dialogFormVisible: false,
        testContentVisible: false,
        btnEditText: '提 交',
        formTitle: '创建数据源',
        formTitle01: '测试连接',
        editLoading: false,
        rules: {
          datasource_name: [
            {required: true, message: '请输入名称', trigger: 'blur'},
            {validator: util.validateString, trigger: 'blur'}
            ],
          dbtype: [{required: true, message: '请选择数据库类型', trigger: 'change'}],
          ip: [
            {required: true, message: '请输入IP地址', trigger: 'change'},
            {
              validator: (rule, value, callback) => {
                let re = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])(\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){3}$/
                if (!value.match(re)) {
                  callback(new Error('输入有误'))
                } else {
                  callback();
                }
              }
            }
          ],
          port: [
            {required: true, message: '请输入端口号', trigger: 'change'},
            {
              validator: (rule, value, callback) => {
                let n = parseInt(value)
                if (isNaN(n)) {
                  callback(new Error('输入有误'))
                } else if (n < 0) {
                  callback(new Error('必须为正整数'))
                } else {
                  callback();
                }
              }
            }
          ],
          db_user_name: [
            {required: true, message: '请输入用户名', trigger: 'blur'},
            {validator: util.validateString, trigger: 'blur'}
            ],
          dbname: [
            {required: true, message: '请输入数据库名!', trigger: 'blur'},
            //{validator: util.validateString, trigger: 'blur'}
            ],
          dbpwd: [
            {required: true, message: '请输入密码', trigger: 'change'},
            {min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur'},
            //{validator: util.validateString, trigger: 'blur'}
          ]
        },
        form: {
          dbtype: '',
          user_datasource_id: '',
          datasource_name: '',
          ip: '',
          port: '',
          db_user_name: '',
          dbname: '',
          dbpwd: ''
        },
        formLabelWidth: '120px',
        butStatus: {
          update: true,
          func: true,
          data: true,
          add: false,
          rm: true
        },
        multipleSelection: [],
        formInline: {
          allOpts: [{
            key: 'datasource_name',
            label: '名称',
            type: '',
            val: ''
          }, {
            key: 'db_user_name',
            label: '用户名',
            type: '',
            val: ''
          }, {
            key: 'dbname',
            label: '数据库',
            type: '',
            val: ''
          }
          ],
          cOpts: [{
            key: 'datasource_name',
            label: '名称',
            type: '',
            val: ''
          }]
        },
        tableData: [],
        pagination: {
          count: 0,
          start_index: 0,
          page_count: 20,
        },
        percentage: 0
      }
    },
    methods: {
      search (val) {
        //调用查询服务
        this.getTableData();
      },
      addPercentage () {
        clearTimeout(this.timeout);
        this.timeout = setTimeout(() => {
          if (this.percentage < 99) {
            this.percentage += 9
            this.addPercentage()
          } else {
            clearTimeout(this.timeout);
          }
        }, 1000);
      },
      toTest (scope) {
        this.testContentVisible = true
        this.percentage = 0
        this.addPercentage()
        let datasource_id = scope.row.user_datasource_id
        dao.testDatasource({user_datasource_id: datasource_id}).then(res => {
          if (res.FX.err) {
            this.testContentVisible = false;
            return false;
          }
          clearTimeout(this.timeout);
          this.percentage = 100
          this.testContentVisible = false;
          this.$message({
            type: 'success',
            message: '连接成功'
          })
        }).catch(res => {
          this.testContentVisible = false;
          clearTimeout(this.timeout);

        })

        /*this.testContentVisible = true
         let _this = this;
         let t1 = setInterval( ()=> {
         this.testContentVisible == true ? _this.percentage += 9 : clearInterval(t1)
         if(_this.percentage > 90){
         clearInterval(t1)
         let datasource_id = scope.row.user_datasource_id
         dao.testDatasource({user_datasource_id:datasource_id}).then(res=>{
         if(res.FX.err){
         this.testContentVisible = false;
         return false;
         }
         _this.percentage = 100
         this.testContentVisible = false;
         this.$message({
         type:'success',
         message:'连接成功'
         })
         }).catch(res => {
         this.testContentVisible = false;
         })
         }
         },1000);
         _this.percentage = 0*/
      },
      handleSizeChange (val) {
        this.pagination.page_count = val;
        this.getTableData();
      },
      handleCurrentChange (val) {
        this.pagination.start_index = val;
        this.getTableData();
      },
      handleSelectionChange (val) {
        this.multipleSelection = val;
        if (val.length == 1) {
          this.butStatus.rm = false;
          this.butStatus.update = false;
        } else if (val.length > 1) {
          this.butStatus.rm = false;
          this.butStatus.update = true;
        } else {
          this.butStatus.rm = true;
          this.butStatus.update = true;
        }
      },
      editSubmit () {
        this.$refs.form.validate((valid) => {
          if (!valid) return false;
          this.$confirm('确认提交吗？', '提示', {
            type: 'info'
          }).then(() => {
            this.btnEditText = '提交中';
            this.editLoading = true;
            //this.value == 'mysql' ? this.form.dbtype = 1 : this.form.dbtype = 2;
            let obj = this.form;
            let fun = "addDatasource"
            if (obj.user_datasource_id) {
              fun = 'updateDatasource'
            }
            dao[fun](obj).then(res => {
              this.btnEditText = '提 交';
              this.editLoading = false;
              this.dialogFormVisible = false;
              if (!res.body || res.body.retCode != '200') {
                util.apiMsg(res);
                return false;
              }
              this.$message({
                type: 'success',
                message: '提交成功!'
              });
              this.getTableData();
            }).catch(res => {
              this.btnEditText = '提 交';
              this.editLoading = false;
              this.dialogFormVisible = false;
            });
          })
        })
      },
      handleAdd () {
        let obj = {}
        for (let k in this.form) obj[k] = '';
        this.form = obj;
        this.dialogFormVisible = true
      },
      handleUpdate () {
        if (this.multipleSelection.length != 1) return false
        let obj = {}
        for (let k in this.form) obj[k] = this.multipleSelection[0][k]
        obj.dbtype = obj.dbtype + ''
        this.form = obj;
        this.dialogFormVisible = true
      },
      handleDelete () {
        this.$confirm('确认删除吗？', '提示', {
          type: 'info'
        }).then(() => {
          let ids = this.multipleSelection.map(item => {
            return item.user_datasource_id
          })
          dao.deleteDatasource({user_datasource_ids: ids}).then(res => {
            if (!res.body || res.body.retCode != '200') {
              util.apiMsg(res);
              return false;
            }
            this.$message('操作成功')
            this.getTableData()
          }).catch(res => {

          })

        }).catch(res => {

        })
      },
      getTableData () {
        let obj = {
          start_index: this.pagination.start_index,
          page_count: this.pagination.page_count
        }
        this.formInline.cOpts.map(item => {
          obj[item.key] = item.val
        })
        dao.getDatasource(obj).then(res => {
          if (!res.body && res.body.retCode != 200) {
            this.$message(res.body.retMsg);
            return;
          }
          this.tableData = res.body.results;
          this.pagination.count = res.body.count;
        }).catch(res => {
        })
      },
      sizeChange (size) { },
      currentChange(currentPage){ },
      validateDatasourceNameHttp () { //验证数据源名称是否唯一
        if (this.form.datasource_name == "") { return false }
        dao.validateDatasourceName({"validate_name": this.form.datasource_name}).then((response) => {
          if (response.body.retMsg == "1") {
            this.form.zhHelpTips = "任务名称可用";
            this.form.isSuccess = "1";
          } else {
            this.form.zhHelpTips = "任务名称重复";
            this.form.isSuccess = "0";
            return false;
          }
        })
      },
      resetForm () { //重置表单
        this.$refs.form.resetFields();
        this.dialogFormVisible = false;
      }

    },
    mounted() {
      this.getTableData()
    }
  }
</script>

<style scoped>
  span.zhHelpTips {
    color: #13CE66;
  }

  span.zhHelpTipsErr {
    color: #FF4949;
  }
</style>